import ConfirmModal from '@/components/ConfirmModal';
import PlaceHolderCpn from '@/components/PlaceHolderCpn';
import { Auths, Role } from '@/utils/typings.d';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { Tag } from 'antd';
import { useRef, useState } from 'react';
import { useModel } from 'umi';
import AuthEdit from './components/AuthEdit';
import CreateSystemUser from './components/CreateSystemUser';
import UpdateSystemUser from './components/UpdateSystemUser';
import { queryUserList, removeUser } from './service';
import type { SystemUserTableListItem } from './typings.d';

const SystemUserList = () => {
  const { initialState } = useModel('@@initialState');
  const currUser = initialState?.currentUser;
  const auths = currUser?.auth ? new Set(currUser.auth.systemUser || []) : new Set();
  const userRole = currUser?.role;
  const [currSystemUser, setCurrSystemUser] = useState<SystemUserTableListItem | null>(null);
  const [visible, setVisible] = useState<boolean>(false);
  const actionRef = useRef<ActionType>();
  const RoleEnum =
    userRole === Role.ADMIN
      ? {
          admin: <Tag color="red">系统管理</Tag>,
          enterprise: <Tag color="blue">企业管理</Tag>,
          staff: <Tag color="green">企业员工</Tag>,
        }
      : {
          enterprise: <Tag color="red">企业管理</Tag>,
          staff: <Tag color="blue">企业员工</Tag>,
        };
  const ifCreate = auths.has(Auths.CREATE);
  const ifModify = auths.has(Auths.MODIFY);
  const ifDelete = auths.has(Auths.DELETE);
  const columns: ProColumns<SystemUserTableListItem>[] = [
    {
      title: 'id',
      hideInTable: true,
      hideInSearch: true,
      dataIndex: '_id',
    },
    {
      title: '用户名称',
      align: 'center',
      dataIndex: 'userName',
    },
    {
      title: '用户账号',
      dataIndex: 'account',
      align: 'center',
    },
    {
      title: '用户角色',
      width: 70,
      dataIndex: 'role',
      align: 'center',
      hideInSearch: true,
      valueEnum: RoleEnum,
    },
    {
      title: '创建时间',
      width: 200,
      align: 'center',
      dataIndex: 'createTime',
      valueType: 'dateTime',
      hideInSearch: true,
    },
    {
      title: '权限管理',
      align: 'center',
      dataIndex: 'auth',
      hideInSearch: true,
      render: (_, record) =>
        userRole >= record.role ? (
          <PlaceHolderCpn />
        ) : (
          <AuthEdit authId={record.auth} ownerName={record.ownerName} />
        ),
    },
    {
      title: '操作',
      align: 'center',
      key: 'option',
      fixed: 'right',
      valueType: 'option',
      render: (_, record, x, action) => [
        ifModify && (
          <a
            key={`${record._id}_editModal`}
            onClick={() => {
              setCurrSystemUser(record);
              setVisible(true);
            }}
          >
            编辑
          </a>
        ),
        ifDelete && record.role !== Role.ADMIN && record._id !== currUser?._id && (
          <ConfirmModal
            key={`${record._id}_ConfirmModal`}
            reload={() => action?.reload()}
            operFunc={async () => await removeUser(record._id)}
            danger={record.role === Role.ENTERPRISE}
            text={
              record.role === Role.ENTERPRISE
                ? '正在删除[企业管理者]，该操作会删除相关企业所有人员，请慎重操作！'
                : undefined
            }
          />
        ),
      ],
    },
  ];
  return (
    <PageHeaderWrapper title={false} subTitle="系统用户列表">
      <ProTable
        rowKey="_id"
        scroll={{ x: true }}
        style={{ whiteSpace: 'nowrap' }}
        search={{ labelWidth: 'auto' }}
        columns={columns}
        actionRef={actionRef}
        columnEmptyText="暂无数据"
        dateFormatter="string"
        pagination={{
          showQuickJumper: true,
          defaultPageSize: 10,
          size: 'default',
        }}
        request={async (param, sort) => {
          const res = await queryUserList(param, sort);
          return res;
        }}
        toolBarRender={(action) => [
          ifCreate && <CreateSystemUser key="sys_user_create" func={() => action?.reload()} />,
        ]}
      />
      {visible && currSystemUser && (
        <UpdateSystemUser
          visible={visible}
          user={currSystemUser}
          setUnvisible={() => {
            setCurrSystemUser(null);
            setVisible(false);
          }}
          reload={() => {
            actionRef.current?.reload();
          }}
        />
      )}
    </PageHeaderWrapper>
  );
};

export default SystemUserList;
